﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace DotNet.Utilities.Log
{
    public enum LogType { Information = 1, Warning, Error, Debug, SQL };

    /// <summary>
    /// 【Log】：日志的处理类
    ///		日志文件的生成策略由本类自行决定
    /// </summary>
    public sealed class LogTool
    {
        private string _logdirdest;         //日志保存的目录或FileServer的位置

        private static object o_LockHelperLogToDirDest = new object();

        //控制是否写正常的日志，避免日志文件太大,在web config增加定义
        //<add key="IsWriteLog" value="false"/>
        private static bool _isWriteLog = true;

        public LogTool()
        {
            object objIsWriteLog = ConfigurationSettings.AppSettings["IsWriteLog"];
            if (objIsWriteLog != DBNull.Value)
            {
                if (objIsWriteLog != null && objIsWriteLog.ToString().Trim() != "")
                {
                    _isWriteLog = Boolean.Parse(ConfigurationSettings.AppSettings["IsWriteLog"].Trim());
                }
            }
        }

        //public Log(String logDirDest){
        //    object objIsWriteLog = ConfigurationSettings.AppSettings["IsWriteLog"];
        //    if(objIsWriteLog != DBNull.Value)
        //    {
        //        if (objIsWriteLog != null && objIsWriteLog.ToString().Trim()!="")
        //        {
        //            _isWriteLog = Boolean.Parse(ConfigurationSettings.AppSettings["IsWriteLog"].Trim());
        //        }
        //    }
        //    this.SetLogDirDest(logDirDest);
        //}

        ///// <summary>
        ///// 设置日志文件的保存位置
        ///// </summary>
        ///// <param name="logDirDest">位置</param>
        //public void SetLogDirDest(String logDirDest)
        //{
        //    this._logdirdest = LogFormater.DirDestFormat(logDirDest);
        //}

        /// <summary>
        /// 将日志写入指定目录下
        /// </summary>
        /// <param name="lType"></param>
        /// <param name="logText"></param>
        public static void LogToDirDest(LogType lType, string logText, params object[] args)
        {
            LogToDirDest("",  lType, logText, args);
        }

        /// <summary>
        /// 将日志写入指定目录下
        /// </summary>
        /// <param name="logDirDest">指定目录，为空则默认为C:\log\</param>
        /// <param name="lType"></param>
        /// <param name="logText"></param>
        public static void LogToDirDest(string logDirDest, LogType lType, string logText, params object[] args)
        {
            if (_isWriteLog == false)
            {
                return;
            }

            string logFile = "";

            if (string.IsNullOrEmpty(logDirDest))
            {
                logDirDest = "C:\\log\\";
            }

            if (!System.IO.Directory.Exists(logDirDest))
            {
                System.IO.Directory.CreateDirectory(logDirDest);
            }

            switch (lType)
            {
                case LogType.Information:
                    logFile = logDirDest + System.DateTime.Now.ToString("yyyy-MM-dd").Replace("-", "") + ".log";
                    break;
                case LogType.Warning:
                    logFile = logDirDest + System.DateTime.Now.ToString("yyyy-MM-dd").Replace("-", "") + ".warning";
                    break;
                case LogType.Error:
                    logFile = logDirDest + System.DateTime.Now.ToString("yyyy-MM-dd").Replace("-", "") + ".error";
                    break;
                case LogType.Debug:
                    logFile = logDirDest + System.DateTime.Now.ToString("yyyy-MM-dd").Replace("-", "") + ".debug";
                    break;
                case LogType.SQL:
                    logFile = logDirDest + System.DateTime.Now.ToString("yyyy-MM-dd").Replace("-", "") + ".sql";
                    break;
                default:
                    logFile = logDirDest + System.DateTime.Now.ToString("yyyy-MM-dd").Replace("-", "") + ".log";
                    break;
            }

            logText = "[" + System.DateTime.Now.ToString() + "] " + string.Format(logText, args) + "\r\n-------------\r\n";
            byte[] logBytes = System.Text.Encoding.UTF8.GetBytes(logText);

            //锁定（线程安全）
            lock (o_LockHelperLogToDirDest)
            {
                System.IO.FileStream file = System.IO.File.Open(logFile, System.IO.FileMode.OpenOrCreate);
                try
                {
                    file.Seek(0, System.IO.SeekOrigin.End);
                    file.Write(logBytes, 0, logBytes.Length);
                }
                finally
                {
                    if (file != null) file.Close();
                }
            }
        }

        /// <summary>
        /// 将日志写入指定文件中。
        /// </summary>
        /// <param name="logDirDest">文件路径，为空则默认为C:\{当前日期}.log</param>
        /// <param name="logText"></param>
        /// <param name="lType"></param>
        public static void LogToFileDest(string logText, LogType lType)
        {
            LogToFileDest("", "", LogType.Debug);
        }

        /// <summary>
        /// 将日志写入指定文件中。
        /// </summary>
        /// <param name="logDirDest">文件路径，为空则默认为C:\{当前日期}.log</param>
        /// <param name="logText"></param>
        /// <param name="lType"></param>
        public static void LogToFileDest(string logFileDest, string logText, LogType lType)
        {
            try
            {
                if (string.IsNullOrEmpty(logFileDest))
                    logFileDest = DateTime.Now.ToShortDateString();

                string logFile = "";
                //如果文件不存在，创建文件   
                switch (lType)
                {
                    case LogType.Information:
                        logFile = logFileDest + ".log";
                        break;
                    case LogType.Warning:
                        logFile = logFileDest + ".warning";
                        break;
                    case LogType.Error:
                        logFile = logFileDest + ".error";
                        break;
                    case LogType.Debug:
                        logFile = logFileDest + ".debug";
                        break;
                    default:
                        logFile = logFileDest + ".log";
                        break;
                }

                logText = "[" + System.DateTime.Now.ToString() + "] " + logText + "\r\n-------------\r\n";
                byte[] logBytes = System.Text.Encoding.UTF8.GetBytes(logText);

                //锁定（线程安全）
                lock (o_LockHelperLogToDirDest)
                {
                    System.IO.FileStream file = System.IO.File.Open(logFile, System.IO.FileMode.OpenOrCreate);
                    try
                    {
                        file.Seek(0, System.IO.SeekOrigin.End);
                        file.Write(logBytes, 0, logBytes.Length);
                    }
                    finally
                    {
                        if (file != null) file.Close();
                    }
                }
            }
            catch (Exception)
            {

            }
        }

        private static string GetStringFromData(System.Collections.IDictionary iDictionary)
        {
            string p = "";
            foreach (string key in iDictionary.Keys)
            {
                p = p + "KEY=" + key + ";VALUE=" + iDictionary[key] + "***";
            }
            return p;
            //for (int i = 0; i < iDictionary.Count; i++)
            //{
            //    p = p + "KEY=" + iDictionary. + "VALUE=" + iDictionary.Values[i];
            //}

        }
    }
}
